package com.syl.upimg.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.syl.upimg.bean.XiTuBean;
import com.syl.upimg.enums.ImageUploadTypeEnum;
import com.syl.upimg.service.BaseUpload;
import com.syl.upimg.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 掘金羊毛
 *
 * @author syl
 **/
@Service
public class XiTuFleece implements BaseUpload {
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public RestTemplate createRestTemplate() {
        return restTemplate;
    }

    @Override
    public LinkedMultiValueMap<String, Object> getParam(FileSystemResource file, String fileName, String fileType) {
        LinkedMultiValueMap<String, Object> linkedMultiValueMap = new LinkedMultiValueMap<>();
        linkedMultiValueMap.add("file", file);
        return linkedMultiValueMap;
    }

    @Override
    public String[] getLimit() {
        return new String[]{"jpg", "png", "gif", "webp", "tif", "bmp"};
    }

    @Override
    public String getUrl() {
        return "https://cdn-ms.juejin.im/v1/upload?bucket=gold-user-assets";
    }

    public XiTuBean upload(String filePath) throws IOException {
        return this.upload(filePath, false);
    }

    public XiTuBean upload(String filePath, boolean delete) throws IOException {
        long startTime = System.currentTimeMillis();
        XiTuBean xiTuBean = new XiTuBean();
        String json = this.uploadByString(filePath, delete);
        ObjectMapper mapper = JsonUtils.getObjectMapper(false);
        JsonNode jsonNode = mapper.readTree(json);
        JsonNode dataNode = jsonNode.get("d");
        if (dataNode == null) return null;
        JsonNode url = dataNode.get("url");
        JsonNode imageInfo = dataNode.get("imageInfo");
        if (url != null) {
            xiTuBean.setUrl(url.get("http").asText()).setHttpsUrl(url.get("https").asText());
            xiTuBean.setBaseUrl(xiTuBean.getUrl());
        }
        if (imageInfo != null) {
            xiTuBean.setWidth(imageInfo.get("width").asInt());
            xiTuBean.setHeight(imageInfo.get("height").asInt());
            xiTuBean.setFormat(imageInfo.get("format").asText());
            xiTuBean.setSize(imageInfo.get("size").asInt());
        }
        long endTime = System.currentTimeMillis();
        int intValue = new Long(endTime - startTime).intValue();
        xiTuBean.setTimerMs(intValue).setImageUploadTypeEnum(ImageUploadTypeEnum.XT);
        return xiTuBean;
    }

}
